<template>
  <el-container class="layout-container" style="height: 95%">
    <el-container>
      <el-main>
        <el-scrollbar>
          <!-- 查询表单 -->
          <PileDataQueryTimeForm @queryData="select" :queryParams="queryParams" />

          <!-- 数据表格 -->
          <el-card class="mb-4">
            <el-table
                :data="pileData"
                style="width: 100%"
                border
                stripe
                @row-click="pileClick"
                highlight-current-row
            >

              <el-table-column prop="pileNumber" label="桩基号" align="center" />
              <el-table-column prop="pileDiameter" label="桩径(m)" align="center" />
              <el-table-column prop="pileLength" label="桩长(m)" align="center" />
              <el-table-column prop="steelCageLength" label="钢筋笼长度(m)" align="center" />
              <el-table-column prop="overPouringLength" label="超灌长度(m)" align="center" />

              <el-table-column label="钢筋工程量(kg)" align="center">
                <template #default="scope">
                  <span v-if="scope.row.pileLength !== undefined">
                     {{ steelQuantity(scope.row) }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>

              <el-table-column label="砼设计量(m³)" align="center">
                <template #default="scope">
                  <span v-if="scope.row.pileLength !== undefined" >
                   <a >{{ pouringQuantity(scope.row) }}</a>
                  </span>
                  <span v-else>-</span>

                </template>
              </el-table-column>

              <el-table-column label="砼实际量(m³)" align="center">
                <template #default="scope">
                  <span :style="{ color: scope.row.actualPouringVolume ? 'default' : 'red' }" @dblclick="startEditing(scope.row,'actualPouringVolume',scope.row.actualPouringVolume,false)">{{ scope.row.actualPouringVolume?scope.row.actualPouringVolume:"缺失" }}</span>
                </template>
              </el-table-column>



              <el-table-column prop="pouringTime" label="浇筑时间" align="center">
                <template #default="scope">

                  <span @dblclick="startEditing(scope.row,'pouringTime',scope.row.pouringTime,true)">{{ formatDateTime(scope.row.pouringTime) }}</span>
                </template>
              </el-table-column>

              <el-table-column label="试块编号" align="center">
                <template #default="scope">
                  <span :style="{ color: scope.row.testBlockNumber ? 'default' : 'red' }" @dblclick="startEditing(scope.row,'testBlockNumber',scope.row.testBlockNumber,false)">{{ scope.row.testBlockNumber?scope.row.testBlockNumber:"缺失" }}</span>

                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" min-width="200" align="center">
                <template #default="scope">
                  <el-button
                      type="primary"
                      size="small"
                      @click="showInfo(scope.row)"
                      class="mr-2"
                  >
                    <el-icon><Edit /></el-icon> 内页资料
                  </el-button>
                  <el-button
                      type="primary"
                      size="small"
                      @click="showInfo(scope.row)"
                      class="mr-2"
                  >
                    <el-icon><Document /></el-icon> 施工详情
                  </el-button>

                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <!-- 分页组件 -->
          <el-pagination
              class="flex justify-center mt-4"
              background
              layout="prev, pager, next, total"
              :current-page="currentPage"
              :page-size="itemsPerPage"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />


        </el-scrollbar>
        <!--   编辑框     -->
        <div v-if="isEditOpen" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div class="bg-white rounded-lg p-4 max-w-sm w-full mx-4 transform transition-all shadow-lg">
            <div class="flex justify-between items-center mb-3 border-b border-gray-200 pb-2">
              <el-date-picker
                  v-if="isTime"
                  v-model="editValue"
                  @keyup.enter="save"
                  @blur="save"
                  type="datetime"
                  placeholder="请选择日期时间"
                  class="w-full"
              >
              </el-date-picker>
              <input  v-else v-model="editValue"   @keyup.enter="save" @blur="save" placeholder="请输入内容" class="w-full border-none outline-none" />
            </div>
            <div class="flex justify-between items-center mb-3">
              <button class="bg-red-500 hover:bg-red-600 text-white px-3 py-1.5 rounded-lg transition-colors flex items-center space-x-1" @click="cancel">
                <i class="fa fa-trash mr-1"></i>
                <span>取消</span>
              </button>
              <button class="bg-green-500 hover:bg-green-600 text-white px-3 py-1.5 rounded-lg transition-colors flex items-center space-x-1" @click="save">
                <i class="fa fa-check mr-1"></i>
                <span>修改</span>
              </button>
            </div>
          </div>

        </div>

      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { Edit, Document } from '@element-plus/icons-vue';
import PileDataEdit from '@/views/pile/components/PileDataEdit.vue';
import {countCompletedPilesByTimeAPI, putPileAPI} from '@/apis/api_pile';
import PileDataQueryTimeForm from '@/views/pile/components/PileDataQueryTimeForm.vue';
import PileExcelPouringExport from '@/views/pile/components/pileExcelPouringExport.vue';
import router from "@/router/index.js";

// 数据状态
const pileData = ref([]);
const currentPage = ref(1);
const itemsPerPage = ref(10); // 调整为更合理的每页数量
const totalPages = ref(1);
const total = ref(1);
const queryParams = ref({
  startTime: "",
  endTime: "",
  sort: false
});
/**
 * 钢筋工程量
 * @param row
 * @returns {string}
 */
const steelQuantity = (row)=>{
  const length=row.pileLength;
  const s25=3.85*24*(length+1.125);
  const s10=0.617*Math.sqrt(
      length*length
      +((length+5)/0.2*Math.PI*(row.pileDiameter-0.05*2))
      *((length+5)/0.2*Math.PI*(row.pileDiameter-0.05*2))
  );
  const s20=2.47*Math.ceil(length/2)*((row.pileDiameter-0.09*2)*Math.PI+3.3775);
  console.log(s10,s20,s25)
  const q= (s10+s20+s25).toFixed(3)
  return q;
}
/**
 * 混凝土工程量
 * @param row
 * @returns {string}
 */
const pouringQuantity = (row)=>{

  const length=row.pileLength+row.overPouringLength;
  const r=row.pileDiameter/2
  return (length*r*r*Math.PI).toFixed(3);
}
// 初始化查询参数
const initQueryParams = () => {
  const endTime = new Date();
  const startOfMonth = new Date(endTime.getFullYear(), endTime.getMonth(), 1);
  startOfMonth.setFullYear(2025,3,13)
  startOfMonth.setHours(18,31,0,0)
  queryParams.value = {
    startTime: formatISO(startOfMonth),
    endTime: formatISO(endTime),
    sort: true
  };

  console.log("初始化参数", queryParams.value);
};

// 格式化日期为ISO字符串
const formatISO = (date) => date.toISOString().split('.')[0] + 'Z';

// 获取桩基数据
const getPileData = async () => {
  try {
    const res = await countCompletedPilesByTimeAPI(
        currentPage.value,
        itemsPerPage.value,
        queryParams.value
    );

    pileData.value = res.data.records || [];
    totalPages.value = Math.ceil(res.data.total / itemsPerPage.value);
    total.value = res.data.total;
  } catch (error) {
    console.error("获取桩基数据失败", error);
    ElMessage.error("获取数据失败，请稍后重试");
  }
};

// 查询数据
const select = (data) => {
  console.log("按时间查询", data);
  queryParams.value = data;
  getPileData();
};

// 表格行点击事件
const pileClick = (row) => {
  console.log('选中行数据', row);
};

// 分页控制
const handleSizeChange = (newSize) => {
  itemsPerPage.value = newSize;
  getPileData();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getPileData();
};

//

const showInfo=(row)=>{
  router.push(`/pile/pileInfo/${row.pileNumber}`);
}
// 编辑行数据
const editRef = ref(null);
const editRow = (row) => {
  console.log("编辑行数据", row);
  editRef.value.openDialog(row);
};

// 生成资料
const createRef = ref(null);
const CreatExportRow = (row) => {
  console.log('生成资料', row);
  createRef.value.openDownDialog(row);
};

// 保存数据
const handleSave = (updatedData) => {
  const index = pileData.value.findIndex((item) => item.id === updatedData.id);
  if (index !== -1) {
    pileData.value[index] = updatedData;
  }
  getPileData();
};

// 组件挂载后初始化
onMounted(() => {
  initQueryParams();
  getPileData();
});


//------------------------------------------------------------------------------------

const isTime=ref(false)
const isEditOpen=ref()
const editKey=ref()
const editValue=ref()
const pile=ref({})
const startEditing=(row,key,value,ist)=>{
  pile.value=row
  isEditOpen.value=true;
  editKey.value=key;
  editValue.value= value
  isTime.value=ist;

}

const cancel=async ()=>{
  isEditOpen.value=false;

  // 保存要复制的值到临时变量，确保不会被后续操作清空
  const textToCopy = editValue.value;

  // 使用增强版复制函数
  const copySuccess = await enhancedCopyToClipboard(textToCopy);

  if (copySuccess) {
    showToast('复制成功！')
  } else {
    showToast('复制失败，请手动复制', 'error')
  }
}
//---------------------------------
const save = async () => {
  console.log(pile.value.actualPouringVolume)
  pile.value[editKey.value] = editValue.value
  await putPileAPI(pile.value)
  isEditOpen.value = false;
  editKey.value = ""
  editValue.value = "";
  await getPileData();
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未记录';

  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
/* 优化表格样式 */
.el-table th {
  background-color: #f5f7fa;
  font-weight: 600;
}

.el-table td {
  padding: 8px 0;
}

/* 按钮样式优化 */
.el-button {
  transition: all 0.2s ease;
}

.el-button:hover {
  transform: translateY(-1px);
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
}

/* 卡片样式 */
.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.custom-tooltip {
  min-width: 200px;
  text-align: left;
  line-height: 1.6;
}

.divider {
  border-top: 1px solid #eee;
  margin: 6px 0;
}
</style>